package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.example.common.R;
import org.example.entity.Users;
import org.example.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO 类描述
 *
 * @author shaoxuan.
 * @date 2024/1/31 0:57
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UsersService service;

    @PostMapping("/add")
    @ApiOperation("用户注册 ")
    public R<Users> add(@RequestBody Users users){
        Users one = service.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, users.getUsername()));
        if (one!=null){
            return R.error("用户名已存在");
        }
        String password = users.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        users.setPassword(md5Password);
        boolean save = service.save(users);
        if(save){
            return R.success(users).setMsg("注册成功");
        }else {
            return R.error("注册失败");
        }
    }

    @PostMapping("/login")
    @ApiOperation("用户登录 ")
    public R<Users> login(@RequestBody Users users){
        Users one = service.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, users.getUsername()));
        if (one==null){
            return R.error("用户名不存在");
        }else {
            String password = DigestUtils.md5DigestAsHex(users.getPassword().getBytes());
            if(one.getPassword().equals(password)){
                return R.success(users).setMsg("登录成功");
            }else {
                return R.error("密码错误");
            }
        }


    }
}
